import msessage from "../util/vue-message.js";

const ERROR_MSG = {
    ECONNABORTED: "请求超时,请稍后重试",
    ETIMEDOUT: "网络异常,请检查网络连接",
    ERR_NETWORK: "网络异常,请检查网络连接"
}
const HTTP_MSG = {
    401: "未授权",
    403: "未授权",
    404: "您所访问的资源不存在",
    500: "服务器异常,请联系管理员",
    DEFAULT: "服务器忙,请稍后重试"
}

axios.defaults.baseURL = "http://127.0.0.1:3000"

axios.interceptors.response.use(
    function (response) {
        return response.data
    },
    function (error) {
        let title = "运行错误,请联系管理员";
        let icon = "error";
        if (error instanceof axios.AxiosError) {
            let { status, code } = error.toJSON();
            if (code == "ECONNABORTED") icon = "warning";
            if (status) {
                title = HTTP_MSG[status] || HTTP_MSG.DEFAULT;
            } else {
                title = ERROR_MSG[code];
            }
        }
        msessage.showTip(title,"",icon)
        return Promise.reject(error);
    }
)

const loadTypes = function(){
    // ajax的数据请求
    return axios({
        url:"/public/types",
        method:"get"
    })
}
const loadFilms = function(){
    // ajax的数据请求
    return axios({
        url:"/public/films",
        method:"get"
    })
}

export default {
    install:function(app){
        app.config.globalProperties.$api = {
            loadTypes,loadFilms
        }
    }
}